package com.wang.back.servlet;

import com.wang.common.pojo.ApiResponse;
import com.wang.common.servlet.BaseServlet;
import com.wang.common.util.PageInfoUtil;
import com.wang.users.pojo.AUsers;
import com.wang.users.pojo.AUsers;
import com.wang.users.service.IUsersDbService;
import com.wang.users.service.impl.UsersDbServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 第二个Servlet 只存储和管理员息息相关的信息 登陆后的操作
 *
 * @author wangshMac
 */
@WebServlet(urlPatterns = "/back/UsersBackServlet")
public class UsersBackServlet extends BaseServlet {
    private IUsersDbService usersDbService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        UsersDbServiceImpl usersDbServiceImpl = new UsersDbServiceImpl();
        this.usersDbService = usersDbServiceImpl;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /* 接收参数 */
        String method = request.getParameter("method");
        if ("main".equalsIgnoreCase(method)) {
            /* 登陆后首页 */
            main(request, response);
        } else if ("usersList".equalsIgnoreCase(method)) {
            usersList(request, response);
        } else if ("usersInsert".equalsIgnoreCase(method)) {
            usersInsert(request, response);
        } else if ("usersInsertSubmit".equalsIgnoreCase(method)) {
            usersInsertSubmit(request, response);
        } else if ("usersUpdate".equalsIgnoreCase(method)) {
            usersUpdate(request, response);
        } else if ("usersUpdateSubmit".equalsIgnoreCase(method)) {
            usersUpdateSubmit(request, response);
        } else if ("usersBatch".equalsIgnoreCase(method)) {
            usersBatch(request, response);
        } else if ("usersDelete".equalsIgnoreCase(method)) {
            usersDelete(request, response);
        }
    }

    private void usersDelete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        Map<String,Object> condMap = new HashMap<>();
        condMap.put("id", id);
        ApiResponse<Object> dbResponse = this.usersDbService.deleteOneUsersService(condMap);
        this.printOut(dbResponse.toJSON().toJSONString(), response);
    }

    private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/back/admins/mainUsers.jsp";
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 用户列表
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void usersList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/back/users/usersList.jsp";

        /* 分页信息 */
        PageInfoUtil pageInfoUtil = this.proccedPageInfo(request);
        /* 搜索条件,生成公共的搜索条件 */
        Map<String, Object> condMap = this.proccedSearch(request);

        String teacherId = request.getParameter("teacherId");
        condMap.put("teacherId", teacherId);
        request.setAttribute("teacherId", teacherId);

        String usersType = request.getParameter("usersType");
        condMap.put("usersType", usersType);
        request.setAttribute("usersType", usersType);

        /* 查询数据库
         * 所有的数据以JSON的形式返回
         *  */
        ApiResponse<AUsers> apiResponse = this.usersDbService.findCondListUsersService(pageInfoUtil, condMap);
        /* 将结果存储到Request中 */
        request.setAttribute("response", apiResponse.toJSON());

        String operType = request.getParameter("operType");
        if ("select".equalsIgnoreCase(operType)) {
            path = "/WEB-INF/jsp/back/users/usersSelectList.jsp";
        }
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 用户添加(打开添加页面)
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void usersInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/back/users/usersInsert.jsp";
        ApiResponse<AUsers> apiResponse = new ApiResponse<>();
        /* 将结果存储到Request中 */
        request.setAttribute("response", apiResponse.toJSON());
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 用户添加(打开添加提交)
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void usersInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String nickName = request.getParameter("nickName");
        String trueName = request.getParameter("trueName");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String usersType = request.getParameter("usersType");
        String sex = request.getParameter("sex");

        /* 接收参数 */
        AUsers users = new AUsers();

        users.setEmail(email);
        users.setNickName(nickName);
        users.setTrueName(trueName);
        users.setUsersType(Byte.parseByte(usersType));
        users.setPassword(password);
        users.setPhone(phone);
        users.setSex(Byte.parseByte(sex));
        ApiResponse<Object> dbResponse = this.usersDbService.saveOneUsersService(users);
        this.printOut(dbResponse.toJSON().toJSONString(), response);
    }

    /**
     * 用户添加(打开更新页面)
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void usersUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/back/users/usersInfo.jsp";
        String id = request.getParameter("id");
        Map<String,Object> condMap = new HashMap<>();
        condMap.put("id", id);
        ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
        /* 将结果存储到Request中 */
        request.setAttribute("response", apiResponse.toJSON());
        String operType = request.getParameter("operType");
        if ("updateInfo".equalsIgnoreCase(operType)) {
            /* 修改个人信息 */
            this.path = "/WEB-INF/jsp/back/users/usersUpdate.jsp";
        }else if ("resetPassword".equalsIgnoreCase(operType)) {
            /* 重置密码 */
            this.path = "/WEB-INF/jsp/back/users/usersResetPass.jsp";
        }
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 用户添加(打开更新提交)
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void usersUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Map<String,Object> condMap = new HashMap<>();
        condMap.put("id", id);
        ApiResponse<AUsers> dbResUsersService = this.usersDbService.findOneUsersService(condMap);
        /* 接收参数 */
        AUsers users = dbResUsersService.getDataOneJava();

        boolean updateFlag = false;
        String operType = request.getParameter("operType");
        if ("updateInfo".equalsIgnoreCase(operType)) {
            String email = request.getParameter("email");
            String nickName = request.getParameter("nickName");
            String trueName = request.getParameter("trueName");
            String phone = request.getParameter("phone");
            String usersType = request.getParameter("usersType");
            String sex = request.getParameter("sex");
            String status = request.getParameter("status");

            users.setEmail(email);
            users.setNickName(nickName);
            users.setTrueName(trueName);
            users.setUsersType(Byte.parseByte(usersType));
            users.setPhone(phone);
            users.setSex(Byte.parseByte(sex));
            users.setStatus(Byte.parseByte(status));
            updateFlag = true;
        }else if ("resetPassword".equalsIgnoreCase(operType)) {
            String password = request.getParameter("password");
            users.setPassword(password);
            updateFlag = true;
        }
        ApiResponse<Object> dbResponse = new ApiResponse<>();
        if (updateFlag) {
            dbResponse = this.usersDbService.updateOneUsersService(users);
        }
        this.printOut(dbResponse.toJSON().toJSONString(), response);
    }

    /**
     * 用户添加(打开更新提交)
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void usersBatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] idsArr = request.getParameterValues("ids");
        /* 根据teacherId查询所有的学生,将指定老师的学生信息清空 */
        Map<String,Object> condMap = new HashMap<>();
        AUsers users = (AUsers) this.findObjfromSession(request, "users");
        String teacherId = users.getId() + "";
        condMap.put("teacherId", teacherId);
        ApiResponse<AUsers> apiResponseTea = this.usersDbService.findCondListUsersService(null, condMap);
        List<AUsers> dataListJava = apiResponseTea.getDataListJava();
        for (AUsers dataTemp : dataListJava) {
            dataTemp.setTeacherId(0);
            this.usersDbService.updateOneUsersService(dataTemp);
        }

        for (String idTemp : idsArr) {
            condMap.clear();
            condMap.put("id", idTemp);
            ApiResponse<AUsers> dbResUsersService = this.usersDbService.findOneUsersService(condMap);
            /* 接收参数 */
            users = dbResUsersService.getDataOneJava();
            boolean updateFlag = false;
            String operType = request.getParameter("operType");
            if ("updateTeacherId".equalsIgnoreCase(operType)) {
                /* 老师选择学生 */
                users.setTeacherId(Integer.parseInt(teacherId));
                updateFlag = true;
            }
            ApiResponse<Object> dbResponse = new ApiResponse<>();
            if (updateFlag) {
                dbResponse = this.usersDbService.updateOneUsersService(users);
            }
        }
        this.usersList(request, response);
    }
}
